package ru.evga.billboard.editor;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import ru.evga.billboard.graph.preference.ColorParam;
import ru.evga.billboard.graph.preference.IParamChangeListener;
import ru.evga.billboard.graph.preference.IntParam;
import ru.evga.billboard.graph.preference.Param;

public class Utils
{
    
    static public void addNumberControll(JComponent parent, String label, final IntParam param, int step)
    {
        JPanel p = new JPanel();
        p.setLayout(new FlowLayout(FlowLayout.LEFT));
        p.add(new JLabel(label));
        final SpinnerNumberModel m = new SpinnerNumberModel(param.getValue().intValue(), param.getMin().intValue(), param.getMax().intValue(), step);
        
        m.addChangeListener(new ChangeListener()
        {
            @Override
            public void stateChanged(ChangeEvent e)
            {
                m.removeChangeListener(this);
                param.setValue(((Number)m.getValue()).intValue());
                m.addChangeListener(this);
            }
        });
        
        param.addChangeListener(new IParamChangeListener<Integer>()
        {
            @Override
            public void onParamChange(Param<Integer> param)
            {
                m.setValue(param.getValue());
            }
        });

        
        p.add(new JSpinner(m));
        parent.add(p);
    }

    static public void addColorControll(JComponent parent, String label, final ColorParam param)
    {
        JPanel p = new JPanel();
        p.setLayout(new FlowLayout(FlowLayout.LEFT));
        p.add(new JLabel(label));
        final JButton b = new JButton(" ");
        b.setBackground(param.getValue());
        p.add(b);
        final IParamChangeListener<Color> l = new IParamChangeListener<Color>()
        {
            @Override
            public void onParamChange(Param<Color> param)
            {
                b.setBackground(param.getValue());
            }
        };
        b.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                Color c = JColorChooser.showDialog(null, "Choose a color...", b.getBackground());
                if (c != null)
                {
                    b.setBackground(c);
                    param.removeChangeListener(l);
                    param.setValue(c);
                    param.addChangeListener(l);
                }
            }
        });
        
        param.addChangeListener(l);
        parent.add(p);
    }
}
